import westoreStore from '../../store'
import westoreCreate from './create'
import {uuid} from "../utils"

// 缓存changeListener集合
// 这里不能使用Map，因为监听的键可能是一样的
const changeListenerList = [];

// 监控事件值变化
westoreStore.onChange = function (info) {
  changeListenerList && changeListenerList.find((changeListenerItem) => {
    // 如果类型为对象，将改变值直接返回，在callback中自己判断
    if (changeListenerItem.isObject) {
      changeListenerItem.callback(info);
    }
    else {
      // 当前为值类型
      // 当值为undefined时说明该值未更新
      let newValue = info[changeListenerItem.dataKey];
      if (newValue != undefined) {
        changeListenerItem.callback &&
          changeListenerItem.callback(newValue);
      }
    }
  });
}

export default {
  store: westoreStore,
  // 移除监听事件
  addChangeListener(dataKey, callback) {
    let changeID = uuid(8);
    changeListenerList.push({
      changeID,
      dataKey,
      callback,
      isObject: westoreStore.data[dataKey] instanceof Object
    });

    return changeID;
  },
  changeListenerList,
  // 移除监听事件
  removeChangeListener(changeID){
    changeListenerList.find((changeListenerItem,index)=>{
        if(changeListenerItem.changeID == changeID){
          changeListenerList.splice(index ,1);
          return true;
        }
    });
  },
  createPage(pageData) {
    westoreCreate(westoreStore, pageData);
  },

  createComponent(componentData) {
    westoreCreate(componentData);
  }
}